package cn.senwill.service.impl;

import cn.senwill.domain.Result;
import cn.senwill.domain.entity.Stock;
import cn.senwill.mapper.StockMapper;
import cn.senwill.service.StockService;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class StockServiceImpl implements StockService {

    private StockMapper stockMapper;

    @Autowired
    public void setStockMapper(StockMapper stockMapper) {
        this.stockMapper = stockMapper;
    }

    @Override
    public Result update(JSONObject jsonObject) {
//        try {
            Long productId = Long.parseLong(String.valueOf(jsonObject.get("product_id")));
            Integer used = Integer.parseInt(String.valueOf(jsonObject.get("used")));
            Stock stock = stockMapper.selectById(productId);
            if (stock != null) {
                Stock newStock = new Stock();
                newStock.setId(stock.getId());
                newStock.setProductId(stock.getProductId());
                newStock.setTotal(stock.getTotal());
                newStock.setUsed(stock.getUsed() + used);
                newStock.setResidue(stock.getResidue() - used);
                stockMapper.updateById(newStock);
                return Result.success("操作成功 ~", newStock);
            } else {
                throw new RuntimeException("操作失败 -> 该商品仓库为空");
//                return Result.error("操作失败 -> 该商品仓库为空");
            }
//        } catch (Exception e) {
//            return Result.error("操作失败 -> " + e.getMessage());
//        }
    }
}
